<?php





namespace app\mini\controller;





use app\crm\model\Service;

use think\response\Json;

use think\facade\Db;

use app\crm\model\SendMsgModel;



class ServiceLog extends Access

{



    /**

     * 商品列表

     * @return Json

     * @author Mr.Li

     * @create 2021-06-21 14:25

     */

    public function ServiceList(Service $Service): Json

    {

        $this->param = request()->param();

        $this->param['mini'] = 1;

        $customer_id = $this->param['customer_id'] ?? 0;

        // $paramArr['where'] = [['g.status','=',1],['g.is_standard_product','=',1]];

        // $paramArr['field'] = ['g.id', 'g.name', 's.price','s.small_unit_price' ,'g.image','s.item_id','s.unit_id','s.is_small_sales','s.is_big_sales'];

        // print_r($paramArr);exit;

        if($customer_id == 0){

            $data              = [];

            $data['list']      = [];

            $data['dataCount'] = 0;   

        }else{

            $data              = $Service->getDataList($this->param);

        }

        return resultArray(['data' => $data]);



    }



    /**

     * 商品详情

     * @return Json

     * @author Mr.Li

     * @create 2021-06-21 14:25

     */

    public function ServiceLogList(Service $Service): Json

    {

       $this->param = request()->param();

        $this->param['customerId'] = $this->param['customer_id'] ?? 0;

        $this->param['serviceId'] = $this->param['service_id'] ?? 0;

        $data          = $Service->getLogList($this->param);

        return resultArray(['data' => $data]);

    }

    

    /**

     * 服务核销的时候显示的员工列表

     */

     public function readShopPersonList(Service $Service): Json

    {

       $this->param = request()->param();

       $customer_id = $this->param['customer_id'] ?? 0;

       $shopIds  = Db::name('customer')->where('id','=',$customer_id)->column('shop_id');

       $data = Db::name('shop_person')->where('shop_id','in',$shopIds)->column('id,name');

       return resultArray(['data' => $data]);

    }

    



    

    /**

     * 第一步，服务打开二位码的时候

     * @param  Service $serviceModel

     * @return Json

     */

    public function getServiceId(Service $Service): Json

    {

        $this->param = request()->param();

        $service_id = $this->param['service_id'] ?? 0;

        if($service_id == 0){

            return resultArray(['error' => '无法核销，请稍后重试']);

        }

        $returnKey = str_pad($service_id.time(),'20','0',STR_PAD_LEFT);

        $addData['service_id'] = $service_id;

        $addData['key'] = $returnKey;

        try {

            Db::name('service_log_mini_key')->insert($addData);

            return resultArray(['data' => $addData,'error' => '获取成功']);

        } catch (Exception $e) {

            return resultArray(['error' => '系统繁忙请稍后重试']);

        }

        

    }

    

     /**

     * 第二步服务核销

     * @param  Service $serviceModel

     * @return Json

     */

    public function addServiceLog(Service $Service): Json

    {

        $this->param = request()->param();

        $this->param['user_id'] = 0;

        $this->param['pt'] = 1;

        $data = $Service->addServiceLog2($this->param);

        if (!$data) {

            return resultArray(['error' => $Service->getError()]);

        }

        return resultArray(['data' => $data,'error' => $Service->getError()]);

    }

    

    /**

     * 第三步的客户端

     * 客户端服务核销查询

     */

     public function getServiceKey(Service $Service): Json

    {

        $this->param = request()->param();

        $service_id = $this->param['service_id'] ?? 0;

        $key        = $this->param['key'] ?? 0;

        if($service_id == 0){

            return resultArray(['error' => '无法核销，请稍后重试']);

        }

        $where = [];

        array_push($where,['service_id','=',$service_id]);

        array_push($where,['key','=',$key]);

        try {

            $res = Db::name('service_log_mini')->where($where)->find();

            if($res){

                return resultArray(['data' => [],'error' => '获取成功']);

            }

            return resultArray(['error' => '获取失败']);

        } catch (Exception $e) {

            return resultArray(['error' => '系统繁忙请稍后重试']);

        }

    }

    

    /**

     * 第四步客户端

     * 客户确认核销

     */

    public function saveServiceKey4()

    {

        $this->param = request()->param();

        $service_id = $this->param['service_id'] ?? 0;

        $key        = $this->param['key'] ?? 0;

        if($service_id == 0){

            return resultArray(['error' => '无法核销，请稍后重试']);

        }

        $where = [];

        array_push($where,['service_id','=',$service_id]);

        array_push($where,['key','=',$key]);

        try {

            $res = Db::name('service_log_mini')->where($where)->select();

            if(!$res){

                return resultArray(['error' => '无法核销，请稍后重试']);

            }

            $addData = [];

            foreach ($res as $key => $val){

                $customer_id = $val['customer_id'];

                $one = $val;

                unset($one['key']);

                unset($one['status']);

                array_push($addData,$one);

            }

            $saveCustomer['final_service'] = time();

            Db::name('customer')->where('id','=',$customer_id)->update($saveCustomer);

            $sy_num = Db::name('service_log')->where('service_id','=',$service_id)->count() ?? 0;

            $serviceInfo = Db::name('service')->where('id','=',$service_id)->find() ?? 0;

            $num = count($res);

            if (bcadd($num,$sy_num) == $serviceInfo['num']) {

                $saveData = [

                    'status'=>2,

                    'gb_end_time'=>time(),

                ];

                 $this->where('id','=',$serviceId)->save($saveData);

            }

            Db::name('service_log')->insertAll($addData);

            Db::name('service_log_mini')->where($where)->save(['status'=>1]);

            return resultArray(['data' => [],'error' => '获取成功']);

        } catch (Exception $e) {

            return resultArray(['error' => '系统繁忙请稍后重试']);

        }

    }

    

    /**

     * 第五部员工端刷新

     * 员工端服务完成

     */

    public function saveServiceKey5()

    {

        $this->param = request()->param();

        $service_id = $this->param['service_id'] ?? 0;

        $key        = $this->param['key'] ?? 0;

        if($service_id == 0){

            return resultArray(['error' => '正在核销，请稍后重试']);

        }

        $where = [];

        array_push($where,['service_id','=',$service_id]);

        array_push($where,['key','=',$key]);

        // array_push($where,['status','=',1]);

        try {

            $res = Db::name('service_log_mini')->where($where)->find();

            if(!$res){

                return resultArray(['error' => '正在核销，请稍后重试']);

            }

            if($res['status'] != 1){

                return resultArray(['error' => '正在核销，请稍后重试']);

            }

            return resultArray(['data' => [],'error' => '获取成功']);

        } catch (Exception $e) {

            return resultArray(['error' => '系统繁忙请稍后重试']);

        }

    }

    

    /**

     * 第一步，服务打开二位码的时候

     * @param  Service $serviceModel

     * @return Json

     */

    public function getServiceIds(Service $Service): Json

    {

        $this->param = request()->param();

        $customer_id = $this->param['customer_id'] ?? 0;

        if($customer_id == 0){

            return resultArray(['error' => '无法核销，请稍后重试']);

        }

        $returnKey = str_pad($customer_id.time(),'20','0',STR_PAD_LEFT);

        $addData['customer_id'] = $customer_id;

        $addData['key'] = $returnKey;

        // print_r($addData);exit;

        try {

            Db::name('service_log_mini_key')->insert($addData);

            return resultArray(['data' => $addData,'error' => '获取成功']);

        } catch (Exception $e) {

            return resultArray(['error' => '系统繁忙请稍后重试']);

        }

        

    }

    /**

     * 第二部-员工端展示客户未使用的服务列表或选择的未使用的服务列表

     */

     public function getNoUseServerList(Service $Service)

     {

        $this->param = request()->param();

        $this->param['user_id'] = 0;

        $this->param['pt'] = 1;

        $this->param['mini'] = 1;

        $data = $Service->getNoUseDataList($this->param);

        if (!$data) {

            return resultArray(['error' => $Service->getError()]);

        }

        return resultArray(['data' => $data,'error' => $Service->getError()]);

     }

     /**

     * 第三步-员工端-录入核销记录并提交

     * @param  Service $serviceModel

     * @return Json

     */

    public function addServiceLogs(Service $Service): Json

    {

        $this->param = request()->param();

        $this->param['user_id'] = 0;

        $this->param['mini'] = 1;

        $data = $Service->addServiceLog3($this->param);

        if (!$data) {

            return resultArray(['error' => $Service->getError()]);

        }

        return resultArray(['data' => $data,'error' => $Service->getError()]);

    }
    public function addServiceLogs2(Service $Service): Json

    {

        $this->param = request()->param();

        $this->param['user_id'] = 0;

        $this->param['mini'] = 1;

        $data = $Service->addServiceLog4($this->param);

        if (!$data) {

            return resultArray(['error' => $Service->getError()]);

        }

        return resultArray(['data' => $data,'error' => $Service->getError()]);

    }
    public function addServiceLogs3(Service $Service): Json

    {

        $this->param = request()->param();

        $this->param['user_id'] = 0;

        $this->param['mini'] = 1;

        try{
            foreach($this->param['serviceList'] as $value)
            {
                $params = [];
                $params['customer_id'] = $this->param['customer_id'];
                $params['key'] = $this->param['key']??"";
                $params['bookId'] = $this->param['bookId'];
                $params['mark'] = $this->param['mark']?? 0;
                $params['nurse_id_one'] = $value['nurse1'];
                $params['nurse_id_two'] = $value['nurse2'];
                $params['serviceList'] = $value;
                $data = $Service->addServiceLog5($params);
            }
        } catch (\Exception $e) {
            return resultArray(['error' => $Service->getError()]);
        }
        if (!$data) {

            return resultArray(['error' => $Service->getError()]);

        }

        return resultArray(['data' => $data,'error' => $Service->getError()]);

    }

    

    /**

     * 第三步的客户端

     * 客户端服务核销查询

     */

     public function getServiceKeys(Service $Service): Json

    {

        $this->param = request()->param();

        $customer_id = $this->param['customer_id'] ?? 0;

        $key        = $this->param['key'] ?? 0;

        if($customer_id == 0){

            return resultArray(['error' => '无法核销，请稍后重试']);

        }

        $where = [];

        $telephone222 = Db::name('customer')->where('id', '=', $customer_id)->value('telephone');

        $customerIds222 = Db::name('customer')->where('telephone', '=', $telephone222)->column('id');

        array_push($where, ['customer_id', 'in', $customerIds222]);

        // array_push($where,['customer_id','=',$customer_id]);

        array_push($where,['key','=',$key]);

        try {

            $res = Db::name('service_log_mini')->where($where)->group('service_id')->field('service_id,count(service_id) as num,id,goods_id,nurse_id_one,nurse_id_two')->select()->toArray();

            if($res){

                $list = [];

                $goodsIds = array_values(array_unique(array_column($res,'goods_id')));

                $goodsList = Db::name('shop_goods')->where('id','in',$goodsIds)->column('name','id');

                $serviceIdArr = array_values(array_unique(array_column($res, 'service_id')));

                $service_logList = Db::name('service_log')->where('service_id','in',$serviceIdArr)->group('service_id')->column('count(service_id)', 'service_id');

                $serviceList = Db::name('service')->where('id','in',$serviceIdArr)->column('num,start_time,end_time,service_type', 'id');

                // print_r($serviceList);exit;

                $nurse_id_oneArr = array_values(array_unique(array_column($res, 'nurse_id_one')));

                $nurse_id_twoArr = array_values(array_unique(array_column($res, 'nurse_id_two')));

                $nurseArr = array_values(array_unique(array_merge($nurse_id_oneArr,$nurse_id_twoArr)));

                // print_r($nurseArr);exit;

                $personList = Db::name('shop_person')->where('id','in',$nurseArr)->column('name', 'id');

                $nurse_name_one = '';

                $nurse_name_two = '';

                foreach ($res as $key => $val){

                    $one = [];

                    $one['goods_name'] = $goodsList[$val['goods_id']] ?? ''; // 商品名称

                    $one['benci'] = $val['num']; // 本次使用次数

                    $one['sy_num']       = $service_logList[$val['service_id']] ?? 0; // 历史使用

                    $zong = $serviceList[$val['service_id']] ?? [];

                    // print_r($serviceList);

                    // print_r($val);

                    // exit;

                    $zongnum = $zong['num'] ?? 0;

                    $one['yy_num']       = bcsub($zongnum,$one['sy_num']); // 未使用

                    $one['yy_num'] = $one['yy_num'] < 0 ? 0 : $one['yy_num'] ;

                    $start_time = $zong['start_time'] ?? 0;

                    $end_time = $zong['end_time'] ?? 0;

                    $one['start_time'] = $start_time > 0 ? date('Y-m-d H:i:s',$zong['start_time']) : ''; // 开始时间

                    $one['end_time'] = $end_time > 0 ? date('Y-m-d H:i:s',$zong['end_time']) : ''; // 结束时间

                    $one['service_type'] = $zong['service_type'] ?? 0; // 服务类型 1按时间 2按次数

                    $nurse_name_one = $personList[$val['nurse_id_one']] ?? ''; // 一号护理师

                    $nurse_name_two = $personList[$val['nurse_id_two']] ?? ''; // 二号护理师

                    array_push($list,$one);

                }

                if(empty($list)){

                    return resultArray(['error' => '获取失败']);

                }

                return resultArray(['data' => ['list'=>$list,'nurse_name_one'=>$nurse_name_one,'nurse_name_two'=>$nurse_name_two],'error' => '获取成功']);

            }

            return resultArray(['error' => '获取失败']);

        } catch (Exception $e) {

            return resultArray(['error' => '系统繁忙请稍后重试']);

        }

    }

    

    /**

     * 第四步客户端

     * 客户确认核销

     */

    public function saveServiceKeys4()

    {

        $this->param = request()->param();

        $customer_id = $this->param['customer_id'] ?? 0;

        /*
        if($customer_id == '141222'){
            // echo "<pre>";
            // print_r($this->param);
            // echo "</pre>";
            

            // 获取shop_name 
            $shop_name = Db::name('books')->alias('b')->join('shop s', 'b.shop_id=s.shop_id', 'LEFT')->where('b.id',$this->param['bookId'])->value('s.shop_name');

            // 获取顾客手机号
            $tel = Db::name('books')->alias('b')->join('customer c', 'b.customer_id=c.id', 'LEFT')->where('b.id',$this->param['bookId'])->value('c.telephone');

            // echo "核销门店：".$shop_name;
            // echo "<br/>";

            // echo "顾客手机号：".$tel;
            // echo "<br/>";

            // 获取核销内容
            $service_log_content = [];

            $popupList = $this->param['popupList'];

            foreach ($popupList as $key => $value) {
                
                $one = '';

                if($value['service_type'] == '1'){ 
                    // 按期
                    $one = '['.$value['goods_name'].'：次数'.$value['benci'].'，到期时间'.date('Y-m-d',strtotime($value['sy_num'])).']';

                }

                if($value['service_type'] == '2'){
                    // 按次
                    $one = '['.$value['goods_name'].'：次数'.$value['benci'].'，剩余'.$value['sy_num'].']';

                }

                if(!empty($one)){

                    array_push($service_log_content,$one);

                }

            }

            // echo $service_log_str = implode('，',$service_log_content);

            $sendData = [

                'time'    => date('Y-m-d H:i:s'),

                'group'   => $shop_name,

                'content' => implode('，',$service_log_content).',',

            ];

            $sendModel = new SendMsgModel();

            // 短信触达
            // $res = $sendModel->shortMessageServiceLog($tel,$sendData);

            // var_dump($res);

            // echo "<pre>";
            // print_r($data);
            // echo "</pre>";

            // 公众号触达
            // $res = $sendModel->wx_send_service_log();
            exit;

        }
        */

        $key         = $this->param['key'] ?? 0;

        $bookId      = $this->param['bookId'] ?? 0;

        $mobile_model= $this->param['mobile_model'] ?? '';

        $staff_name  = $this->param['staff_name'] ?? '';

        if($customer_id == 0){

            return resultArray(['error' => '无法核销，请稍后重试']);

        }

        $where = [];

        // array_push($where,['customer_id','=',$customer_id]);

        $telephone222 = Db::name('customer')->where('id', '=', $customer_id)->value('telephone');

        $customerIds222 = Db::name('customer')->where('telephone', '=', $telephone222)->column('id');

        array_push($where, ['customer_id', 'in', $customerIds222]);

        array_push($where,['key','=',$key]);

        // print_r($where);exit;

        try {

            $res = Db::name('service_log_mini')->where($where)->select()->toArray();

            if(!$res){

                return resultArray(['error' => '无法核销，请稍后重试']);

            }

            $addData = [];

            foreach ($res as $key => $val){

                $customer_id = $val['customer_id'];

                $one = $val;

                unset($one['key']);

                unset($one['status']);

                unset($one['id']);

                $one['mobile_model'] = $mobile_model;

                $one['station_name'] = $staff_name;

                array_push($addData,$one);

                $sy_num = Db::name('service_log')->where('service_id','=',$val['service_id'])->count() ?? 0;

                $serviceInfo = Db::name('service')->where('id','=',$val['service_id'])->find() ?? [];

                $num = count($res);

                if (bcadd($num,$sy_num) == $serviceInfo['num']) {

                    $saveData = [

                        'status'=>2,

                        'gb_end_time'=>time(),

                    ];

                     Db::name('service')->where('id','=',$val['service_id'])->save($saveData);

                }

            }

            // print_r($res);exit;

            $saveCustomer['final_service'] = time();

            Db::name('customer')->where('id','=',$customer_id)->update($saveCustomer);

            Db::name('service_log')->insertAll($addData);

            // print_r($addData);exit;

            $res = Db::name('service_log_mini')->where($where)->save(['status'=>1]);

            // 预约列表修改核销状态
            $updateBook = [

                'is_use' => 1,

                'is_use_time' => time(),

            ];

            $book_bool = Db::name('books')->where('id','=',$bookId)->update($updateBook);

            $updateBookUseLog = [

                'customer_id' => $customer_id,

                'customer_time' => time(),

            ];

            $bookUseLog_bool = Db::name('books_uselog')->where('book_id','=',$bookId)->update($updateBookUseLog);

            return resultArray(['data' => [],'error' => '获取成功']);

        } catch (Exception $e) {

            return resultArray(['error' => '系统繁忙请稍后重试']);

        }

    }

    

    /**

     * 第五部员工端刷新

     * 员工端服务完成

     */

    public function saveServiceKeys5()

    {

        $this->param = request()->param();

        $customer_id = $this->param['customer_id'] ?? 0;

        $key        = $this->param['key'] ?? 0;

        if($customer_id == 0){

            return resultArray(['error' => '正在核销，请稍后重试']);

        }

        $where = [];

        $telephone222 = Db::name('customer')->where('id', '=', $customer_id)->value('telephone');

        $customerIds222 = Db::name('customer')->where('telephone', '=', $telephone222)->column('id');

        array_push($where,['customer_id','in',$customerIds222]);

        array_push($where,['key','=',$key]);

        array_push($where,['status','=',1]);

        try {

            $res = Db::name('service_log_mini')->where($where)->find();

            if(!$res){

                return resultArray(['error' => '正在核销，请稍后重试']);

            }

            if($res['status'] != 1){

                return resultArray(['error' => '正在核销，请稍后重试']);

            }

            return resultArray(['data' => [],'error' => '获取成功']);

        } catch (Exception $e) {

            return resultArray(['error' => '系统繁忙请稍后重试']);

        }

    }

        /**

     * 客户评论

     */

    public function comment()

    {

        $this->param = request()->param();

        $service_log_id = $this->param['service_log_id'] ?? 0;

        $fraction       = $this->param['fraction'] ?? '';

        $describe       = $this->param['describe'] ?? '';

        if($service_log_id == 0){

            return resultArray(['error' => '请选择评价的服务记录']);

        }

        if ($fraction === '') {

            return resultArray(['error' => '请对该次服务进行评分']);

        }

        $where = [];

        array_push($where,['id','=',$service_log_id]);

        $add['fraction'] = $fraction;

        $add['describe'] = $describe;

        $add['comment_time'] = time();

        try {

            Db::name('service_log')->where($where)->update($add);

            return resultArray(['data' => [],'error' => '评论提交成功']);

        } catch (Exception $e) {

            return resultArray(['error' => '评论提交失败']);

        }

    }

}

